<template>
  <div class="production-plan">
    <el-button type="primary" @click="saveAll">保存主表单和明细</el-button>
    <h3 class="title">货物清单</h3>
    
    <!-- 基本信息 -->
    <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="货品主题">
            <el-input v-model="formData.bomSubject" placeholder="请输入主题" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="货品编号">
            <el-input v-model="formData.documentNo" placeholder="请输入编号" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="制单人员" prop="creator" required>
            <el-input v-model="formData.creator" placeholder="系统自动生成" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注">
            <el-input v-model="formData.remarks" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 父件信息 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="产品名称" >
              <el-input 
              placeholder="请输入" 
              v-model="formData.productName" 
              required
            >
              <template #suffix>
                <el-button size="mini" @click="openAssociatedItemDialog">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产品编码">
            <el-input v-model="formData.productCode" placeholder="请输入"   />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="规格型号">
            <el-input v-model="formData.specificationModel" placeholder="请输入"   />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单位">
          <el-input v-model="formData.unit" placeholder="请输入"  />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="数量">
            <el-input-number v-model="formData.quantity" placeholder="请输入数量" :min="0" :step="1" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产品角色">
            <el-select v-model="formData.productRole" placeholder="产品角色">
              <el-option label="自制" value="自制" />
              <el-option label="委外" value="委外" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工艺流程">
            <el-input v-model="formData.processFlow" placeholder="请填写" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="消耗率">
            <el-input-number v-model="formData.lossRate" placeholder="请输入" :min="0.00" :step="0.01" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 物料明细明细 -->
    <div class="detail-section">
      <h4 class="sub-title">货物明细</h4>
      <el-button size="small" @click="addNewRow">新增行</el-button>
      <el-table :data="planDetailsList" border style="width: 100%">
        <el-table-column label="产品名称" width="180px">
          <template #default="{ row }">
            <el-input 
              v-model="row.productNamess" 
              :readonly="row.isSaved"
            >
              <template #suffix>
                <el-button size="mini" @click="openProductNameDialog(row)">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="产品编号">
          <template #default="{ row }">
            <el-input v-model="row.productCodess" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格型号">
          <template #default="{ row }">
            <el-input v-model="row.specificationModelss" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位">
          <template #default="{ row }">
            <el-input v-model="row.unitss" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="比例">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.productRatio" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="数量">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.quantityss" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="产品角色">
          <template #default="{ row }">
            <el-input v-model="row.productRoless" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="产品角色">
          <template #default="{ row }">
            <el-input v-model="row.processFlowss" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="数量">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.lossRatess" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="方式">
          <template #default="{ row }">
            <el-input v-model="row.pickupMethod" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template #default="{ row }">
            <el-input v-model="row.remarks" type="textarea" rows="3" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
       <el-table-column fixed="right"  label="操作" width="180px">
          <template #default="{ row }">
            <!-- 移除单独保存明细按钮 -->
            <el-button size="small"  type="danger" @click="deleteDetail(row)" :disabled="row.isSaved">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>


     <div id="app">
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span>MinIO 文件上传</span>
        </div>
      </template>
      <el-form ref="formRef1" :model="formData1" label-width="100px">
        <el-form-item label="选择文件">
          <el-upload ref="uploadRef" action="https://localhost:7269/api/FileUpload/UploadFile" :headers="headers"
            :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :http-request="customRequest">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">上传文件</el-button>
        </el-form-item>
      </el-form>
      <el-alert v-if="message" :message="message" :type="messageType" :closable="false" style="margin-top: 20px" />
    </el-card>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="key" label="文件名称" width="200" />
      <el-table-column prop="lastModified" label="创建时间" width="200">
        <template #default="scope">
          {{ new Date(scope.row.lastModified).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="size" label="文件大小" min-width="200" />
      <el-table-column fixed="right" label="操作" min-width="200">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openDeleteDialog(scope.row.key)">
            删除文件
          </el-button>
          <el-button link type="primary" size="small" @click="download(scope.row.key)">下载文件</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="isDeleteDialogVisible" title="删除确认" @close="closeDeleteDialog">
      <p>确定要删除该文件吗？</p>
      <template #footer>
        <el-button @click="closeDeleteDialog">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="isDownloadDialogVisible" title="文件下载">
      <template #content>
        <el-progress :percentage="downloadProgress" :status="downloadStatus"></el-progress>
      </template>
      <template #footer>
        <el-button @click="closeDownloadDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
    <!--物流管理产品名称选择对话框 -->
    <el-dialog
      v-model="associatedItemDialogVisible"
      width="500px"
      title="关联项目选择"
      append-to-body
    >
      <el-table
        :data="associatedItems"
        highlight-current-row
        border
        size="small"
        @current-change="handleAssociatedItemChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column property="productsNumber" label="产品编号" />
        <el-table-column property="productsName" label="产品名称" />
        <el-table-column property="productsNum" label="规格型号" />
        <el-table-column property="productsUnit" label="单位" />
      </el-table>
      <template #footer>
        <el-button @click="pickAssociatedItem">确定</el-button>
      </template>
    </el-dialog>

     <!-- 物理明细产品名称选择对话框 -->
    <el-dialog
      v-model="productNameDialogVisible"
      width="500px"
      title="产品名称选择"
      append-to-body
    >
      <el-table
        :data="productNames"
        highlight-current-row
        border
        size="small"
        @current-change="handleProductNameChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column property="productsNumber" label="产品编号" />
        <el-table-column property="productsName" label="产品名称" />
        <el-table-column property="productsNum" label="规格型号" />
        <el-table-column property="productsUnit" label="单位" />
      </el-table>
      <template #footer>
        <el-button @click="pickProductName">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { Materialread, Materialwrite } from '@/axios/axiosHelper';
import axios from 'axios';
import { th } from 'element-plus/es/locales.mjs';

const formRef = ref(null);
const currentUser = ref("admin");
const router = useRouter();
const route = useRoute();

// 主表单数据
const formData = reactive({
  bomid: '',
  bomSubject: "",
  documentNo: "",
  creator: currentUser.value,
  remarks: "",
  creationTime: new Date().toISOString(),
  productName: "",
  productCode: "",
  specificationModel: "",
  unit: "",
  quantity: 0, // 数字类型
  productRole: "自制",
  processFlow: "",
  lossRate: 0.00, // 数字类型
});

// 主表单验证规则
const rules = reactive({
  bomSubject: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  documentNo: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
});

// 明细数据列表
const planDetailsList = ref([]);
const attachments = ref([]);

// // 保存主表单
// const addjihau = () => {
//   axios.post('https://localhost:7077/api/Ment/AddMaterials', formData)
//     .then(response => {
//       if (response.data.code === 100) {
//         ElMessage.success('保存成功');
//         console.log(response.data.data);
//       } else {
//         ElMessage.error(`保存失败：${response.data.message}`);
//       }
//     })
// };


// 保存主表单和明细
const saveAll =  () => {
  if (formRef.value) {
    const isValid =  formRef.value.validate();
    if (isValid) {

      ElMessage.success('保存成功');
      router.push('/Showhwu');

      // try {
      //   // 保存主表单
      //   const response =  axios.post('https://localhost:7077/api/Ment/AddMaterials', formData);
      //   if (response.data.code === 100) {
      //     formData.bomid = response.data.data.bomid;
         

      //     // 保存明细
      //     const saveDetailPromises = planDetailsList.value.map( (row) => {
      //       const detailWithId = {
      //         ...row,
      //         bomid: formData.bomid
      //       };
      //       const detailResponse =  axios.post(
      //         'https://localhost:7077/api/Ment/AddMaterialsChild',
      //         detailWithId
      //       );
      //       if (detailResponse.data.code === 100) {
      //         row.isSaved = true;
      //         return true;
      //       } else {
      //         ElMessage.error(`明细保存失败：${detailResponse.data.message}`);
      //         return false;
      //       }
      //     });

      //     const results =  Promise.all(saveDetailPromises);
      //     if (results.every(result => result)) {
      //       ElMessage.success('所有明细保存成功');
      //      
      //     }
      //   } else {
      //     ElMessage.error(`主表单保存失败：${response.data.message}`);
      //   }
      // } catch (error) {
      //   // console.error('保存过程中发生错误:', error.response?.data);
      //   // ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
      // }
    }
  }
};

// 新增行
const addNewRow = () => {
  planDetailsList.value.push({
    childID: null,
    productNamess: "",
    productCodess: "",
    specificationModelss: "",
    unitss: "",
    productRatio: '',
    quantityss: '',
    productRoless: "",
    processFlowss: "",
    lossRatess: '',
    pickupMethod: "",
    remarks: "",
    bomid: null,
    // bomiD11: null,
     productInfoFilled: false // 新增标志位，初始化为 false

  });
};


// 产品名称数据
const productNames = ref([]);

const productNameDialogVisible = ref(false);
const currentProductNameRow = ref(null);
const currentProductName = ref({});

// 获取产品信息
const fetchProducts = () => {
  axios.get("https://localhost:7095/api/Products/GetProducts")
    .then(res => {
      productNames.value = res.data.data;
      console.log("产品数据：", productNames.value);
      nextTick(() => {
        // 强制更新表格
      });
    })
    // .catch(error => {
    //   console.error('获取产品信息失败:', error);
    //   ElMessage.error('获取产品信息失败，请检查网络或联系管理员');
    // });
};



// 打开产品名称选择对话框
const openProductNameDialog = (row) => {
  if (productNames.value.length === 0) {
    ElMessage.warning('产品信息正在加载，请稍后重试');
    return;
  }
  currentProductNameRow.value = row;
  productNameDialogVisible.value = true;
};

// 当前选中的产品名称行
const handleProductNameChange = (val) => {
  currentProductName.value = val;
};

// 选择产品名称
const pickProductName = () => {
  if (currentProductName.value && currentProductNameRow.value) {
    currentProductNameRow.value.productNamess = currentProductName.value.productsName;
    currentProductNameRow.value.productCodess = currentProductName.value.productsNumber;
    currentProductNameRow.value.specificationModelss = currentProductName.value.productsNum;
    currentProductNameRow.value.unitss = currentProductName.value.productsUnit;
    currentProductNameRow.value.productInfoFilled = true; // 设置标志位，表示产品信息已填充
    productNameDialogVisible.value = false;
  }
};
onMounted(() => {
fetchAssociatedProjects();
  fetchProducts();

});

// 对话框显示状态
const associatedItemDialogVisible = ref(false);
const currentAssociatedItem = ref({});
// 关联项目数据
const associatedItems = ref([]);
// 打开关联项目选择对话框
const openAssociatedItemDialog = () => {
  associatedItemDialogVisible.value = true;
};
// 当前选中的关联项目行
const handleAssociatedItemChange = (val) => {
  currentAssociatedItem.value = val;
};
// 选择关联项目
const pickAssociatedItem = () => {
  if (currentAssociatedItem.value) {
    formData.productName = currentAssociatedItem.value.productsName; // 产品名称
    formData.productCode = currentAssociatedItem.value.productsNumber; // 产品编号
    formData.specificationModel = currentAssociatedItem.value.productsNum; // 规格型号
    formData.unit = currentAssociatedItem.value.productsUnit; // 单位
    associatedItemDialogVisible.value = false;
  }
};
// 获取关联项目数据
const fetchAssociatedProjects = () => {
  axios.get("https://localhost:7095/api/Products/GetProducts")
    .then(res => {
      associatedItems.value = res.data.data;

    })
    // .catch(error => {
    //   console.error('获取产品信息失败:', error);
    //   ElMessage.error('获取产品信息失败，请检查网络或联系管理员');
    // });
};
//

import { ElDialog } from 'element-plus';


const formRef1 = ref(null);
const uploadRef = ref(null);
const formData1 = ref({});
const message = ref('');
const messageType = ref('');
const tableData = ref([{
  key: "",
  lastModified: "",
  eTag: "",
  size: 0,
  isDir: false,
  versionId: null,
  contentType: null,
  expires: null,
  userMetadata: null,
  isLatest: false,
  lastModifiedDateTime: "",
}]);
const isDeleteDialogVisible = ref(false);
const currentDeleteKey = ref('');
const isDownloadDialogVisible = ref(false);
const downloadProgress = ref(0);
const downloadStatus = ref('');

onMounted(() => {
  listObjects();
});

const download = async (key) => {
  isDownloadDialogVisible.value = true;
  downloadProgress.value = 0;
  downloadStatus.value = 'active';
  try {
    const response = await axios.get(`/api/FileUpload/DownloadFile?objectName=${key}`, {
      responseType: 'blob',
      onDownloadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        downloadProgress.value = percentCompleted;
      }
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', key);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    downloadStatus.value = 'success';
  } catch (error) {
    console.error('文件下载失败:', error);
    message.value = '文件下载失败: ' + (error.response?.data?.error || error.message);
    messageType.value = 'error';
    downloadStatus.value = 'exception';
  }
};

const listObjects = async () => {
  axios.get("https://localhost:7212/api/FileUpload/ListObjectsInOneBucket")
    .then((res) => {
      tableData.value = res.data;
      console.log("查询成功", res.data);
    })
    .catch((err) => {
      console.log(err);
    });
};

const headers = {
  'Content-Type': 'multipart/form-data'
};

const customRequest = async (options) => {
  const formData1 = new FormData();
  formData1.append('file', options.file);
  const response = await axios.post(options.action, formData1, {
    headers: headers
  });
  options.onSuccess(response.data);
  if (response.data != null) {
    alert("添加成功");
    return;
  } else {
    alert("添加失败");
    return;
  }
};

const handleError = (error) => {
  message.value = '上传失败: ' + (error.response?.data?.error || error.message);
  messageType.value = 'error';
};

const submitForm = () => {
  uploadRef.value.submit();
};

const openDeleteDialog = (key) => {
  currentDeleteKey.value = key;
  isDeleteDialogVisible.value = true;
};

const closeDeleteDialog = () => {
  isDeleteDialogVisible.value = false;
  currentDeleteKey.value = '';
};

const confirmDelete = () => {
  axios.delete("https://localhost:7212/api/FileUpload/DeleteObjectInOneBucket", {
    params: {
      objectName: currentDeleteKey.value
    }
  })
    .then((res) => {
      console.log("删除成功", res.data);
      message.value = '文件删除成功';
      messageType.value = 'success';
      listObjects();
      closeDeleteDialog();
    })
    .catch((err) => {
      console.log(err);
      message.value = '文件删除失败: ' + (err.response?.data?.error || err.message);
      messageType.value = 'error';
      closeDeleteDialog();
    });
};

const closeDownloadDialog = () => {
  isDownloadDialogVisible.value = false;
  downloadProgress.value = 0;
  downloadStatus.value = '';
};
</script>

<style scoped>
.production-plan {
  padding: 20px;
}

.title {
  text-align: center;
  margin-bottom: 20px;
}

.sub-title {
  margin: 20px 0 10px;
  font-size: 16px;
  font-weight: 500;
}

.detail-section,
.attachment-section {
  margin-top: 20px;
}

.el-table {
  margin-top: 10px;
}
</style>    